/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[TestSequenceStream.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package io.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

/**
 * 使用SequenceInputStream读取多个文件<br/>
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestSequenceStream {

	/**
	 * 合并多个文件
	 * 
	 * @param outputFileName
	 *            合并后输出的文件名
	 * @param inputFileNames
	 *            待合并的文件名
	 * @throws IOException
	 */
	public static void merge(String outputFileName, String... inputFileNames) throws IOException {
		FileOutputStream out = new FileOutputStream(new File(outputFileName));

		Vector<FileInputStream> ins = new Vector<FileInputStream>();

		for (String inputFileName : inputFileNames) {
			File file = new File(inputFileName);
			FileInputStream in = new FileInputStream(file);
			ins.add(in);
		}

		Enumeration<FileInputStream> e = ins.elements();
		SequenceInputStream sin = new SequenceInputStream(e);

		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = sin.read(buffer)) != -1) {
			out.write(buffer, 0, length);
		}

		sin.close();
		out.close();
	}

	public static void main(String[] args) {
		try {
			String outputFileName = "src/__/s.txt";
			String inputFileName1 = "src/io/api/TestSequenceStream.java";
			String inputFileName2 = "src/io/api/TestSequenceStream.java";
			String inputFileName3 = "src/io/api/TestSequenceStream.java";
			merge(outputFileName, inputFileName1, inputFileName2, inputFileName3);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
